package server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.*;

public class Sjdbc {
    private static Sjdbc myjd=null;
    public static Sjdbc getMyjd(){
        if(myjd==null)
            myjd=new Sjdbc();
        return myjd;
    }//单例模式
    private String CncURL="jdbc:mysql://localhost:3306/db_mngsystest0";//连接的数据库url资源地址
    private String CncUser="root";
    private String CncPwd="Alan124124db";
    private static Connection conn=null;//加载数据库（构造函数）获得的连接
    private Sjdbc(){
        //this.startSQL();//by 文心一言，但似乎用不了
        this.drive();
        conn = this.connectSQL();
    }

    private void startSQL(){//似乎没用的启动sql
        try {
            // 在Windows上启动MySQL服务的命令
            String command = "net start MySQL";

            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = process.waitFor();
            System.out.println("Exited with code: " + exitCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void drive(){
        //加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");//加载驱动
        } catch (ClassNotFoundException e) {
            System.out.println("驱动启动失败。。。未找到数据库类");
            //throw new RuntimeException(e);
        }
        System.out.println("驱动加载成功！！！");

    }
    private Connection connectSQL(){
        //连接数据库
        try {
            Connection myconn = DriverManager.getConnection(CncURL, CncUser, CncPwd);
            System.out.println("数据库连接成功！！！");
            return myconn;
        } catch (SQLException e) {
            System.out.println("数据库连接失败。。。SQL异常");
            return null;
            //throw new RuntimeException(e);
        }
    }
    //
    //外部对jdbc连接的获取//拿着jdbc的连接，即可对sql进行访问
    public Connection getConn(){
        return conn;
    }
    //
    //外部对资源地址、用户名、密码的设置
    public void setCncUser(String iuser){
        CncUser=iuser;
    }
    public void setCncPwd(String ipwd){
        CncPwd=ipwd;
    }
    public void setCncURL(String iurl){
        CncURL=iurl;
    }



    public static void main(String args[]){
        //连接数据库
        //创建执行环境
//        Statement stm = myconn.createStatement();
//        ResultSet rst = stm.executeQuery("select * from student0");
//        for(;rst.next();){
//            System.out.println(
//                    rst.getInt("stuId")+" "+rst.getString("stuname"));
//        }
    }
}
